/**
 * This file Copyright (c) 2003-2009 Magnolia International
 * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the Magnolia
 * Network Agreement and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or MNA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Magnolia Network Agreement (MNA), this file
 * and the accompanying materials are made available under the
 * terms of the MNA which accompanies this distribution, and
 * is available at http://www.magnolia-cms.com/mna.html
 *
 * Any modifications to this file must keep this entire header
 * intact.
 *
 */
package com.google.code.mgnlgroovy.scheduler;

import info.magnolia.commands.CommandsManager;
import info.magnolia.context.Context;
import info.magnolia.context.MgnlContext;
import info.magnolia.context.SimpleContext;

import java.util.Map;

import javax.jcr.RepositoryException;

import org.apache.commons.chain.Command;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.mgnlgroovy.scheduler.manager.JobDefinitionManager;


/**
 * A simple job executing a command. The job reads the command and catalog name out of the jobs context. Parameters to
 * the command are passed by a map under the job data name 'paras'.
 * @author philipp
 * @version $Id: CommandJob.java 3 2009-04-16 22:48:19Z federico.grilli $
 */
public class CommandJob implements Job
{

    private static Logger log = LoggerFactory.getLogger(CommandJob.class);

    private JobDefinitionManager jobDefinitionManager = JobDefinitionManager.Factory.getInstance();

    /**
     * Called by the scheduler. Get the command. Create a magnolia context.
     */
    @SuppressWarnings("unchecked")
    public void execute(JobExecutionContext jobCtx) throws JobExecutionException
    {
        String jobName = jobCtx.getJobDetail().getName();
        log.info("start job [{}]", jobName);
        Map jobData = jobCtx.getJobDetail().getJobDataMap();

        // init context
        MgnlContext.setInstance(new SimpleContext(MgnlContext.getSystemContext()));
        String catalogName = (String) jobData.get(SchedulerConsts.CONFIG_JOB_COMMAND_CATALOG);
        String cmdName = (String) jobData.get(SchedulerConsts.CONFIG_JOB_COMMAND);

        Command cmd = CommandsManager.getInstance().getCommand(catalogName, cmdName);
        if (cmd == null)
        {
            log.error("can't find command {} for job in catalog {}", cmdName, catalogName);
            return;
        }

        Context ctx = new SimpleContext();
        // copy data, else the jobs context could get manipluated by the commands
        ctx.putAll((Map) jobData.get(SchedulerConsts.CONFIG_JOB_PARAMS));

        JobDefinition jd = null;
        try
        {
            jd = jobDefinitionManager.getJobDefinitionByName(jobName);
            if (jd != null)
            {
                jd.setTerminatedWithError(false);
            }
            cmd.execute(ctx);
            log.info("job executed successfully [{}]", jobName);

        }
        catch (Exception e)
        {
            log.error("can't execute command {}-{}. Will be refired {} time(s)", new Object[]{
                catalogName,
                cmdName,
                jobCtx.getRefireCount() }, e);
            
            if (jd != null)
            {
                jd.setTerminatedWithError(true);
            }
            throw new JobExecutionException("can't execute command " + catalogName + "-" + cmdName, e, false);
        }
        finally
        {
            MgnlContext.setInstance(null);
            try
            {
                if (jd != null)
                {
                    jd.setLastFireTime(jobCtx.getFireTime().getTime());
                    jd.setNextFireTime(jobCtx.getNextFireTime().getTime());
                    jobDefinitionManager.saveOrUpdateJobDefinition(jd);
                }
            }
            catch (RepositoryException e)
            {
                log.error(e.getMessage());
            }
        }
    }
}
